<template>
    <div class="subaccount">
        <div class="bottom box-content">
            <div class="move-title">子账户管理</div>
            <div class="middle-box">
                <el-button icon="el-icon-plus" @click="addQquipment">新增用户</el-button>
            </div>
            <div class="middle">
                用户名：<el-input v-model="params.name" placeholder="请输入内容"></el-input>
                手机号：
                <el-input v-model="params.phone" placeholder="请输入内容"></el-input>
                <el-button icon="el-icon-search" @click="queryUser">查询</el-button>
            </div>
            <publicTable
                :columnData="subaccountColumn"
                :tableData="tableData"
                :maxWidth="true"
                style="width: 100%; height: 100%; flex-grow: 0.5"
                v-loading="loading"
            />
            <el-pagination
                :current-page.sync="ym"
                background
                layout="prev, pager, next"
                :total="paging"
                @current-change="onClickPaging"
            />
        </div>
        <public-dialog :dialogVisible.sync="addDialogVisible" :formData="addForm" @submit="addSave" />
        <public-dialog :dialogVisible.sync="editDialogVisible" :formData="editForm" @submit="editSave" />
        <select-dialog :dialogVisible.sync="moveDialogVisible" :formData="moveForm" @submit="moveSave" />
        <delet-dialog
            :dialogVisible.sync="deletDialogVisible"
            @submit="deletSave"
            :formData="{
                title: '提示',
                cancelBtn: '取消',
                saveBtn: '确定',
                message: '是否要删除子账户',
            }"
        />
    </div>
</template>

<script>
import publicTable from '@/components/publicTable';
import deletDialog from '@/components/deletDialog';
import selectDialog from '@/components/selectDialog';
import publicDialog from '@/components/publicDialog';
import {subaccountColumn} from '@/utils/column';
import {
    facilityList,
    facilityAdd,
    facilityDelete,
    facilityAdd1,
    facilityQuery,
    unitList,
    getUnitMap,
} from '@/utils/api';
export default {
    name: 'subaccount',
    components: {
        publicTable,
        publicDialog,
        deletDialog,
        selectDialog,
    },
    data() {
        return {
            paging: 10,
            ym: 1,
            Eid: '',
            subaccountColumn,
            loading: false,
            params: {},
            equipmentList: [],
            equipmentTitle: [],
            tableData: [],
            deleteNews: {},
            amendId: '',
            deleteId: '',
            addDialogVisible: false,
            password: {},
            addForm: {
                formConfig: [
                    {
                        type: 'input',
                        fieldName: 'name',
                        label: '用户名',
                    },
                    {
                        type: 'input',
                        fieldName: 'password',
                        label: '密码',
                    },
                    {
                        type: 'input',
                        fieldName: 'type',
                        label: '用户类型',
                        key: 'fold',
                        options: [
                            {
                                value: '7',
                                label: '普通用户',
                            },
                        ],
                    },

                    {
                        type: 'input',
                        fieldName: 'phone',
                        label: '手机号',
                    },
                    {
                        type: 'input',
                        fieldName: 'email',
                        label: '邮箱',
                    },
                ],
                otherConfig: {
                    title: '新增用户',
                    cancelBtn: '取消',
                    saveBtn: '保存',
                },
                form: {
                    name: '',
                    password: '',
                    type: '7',
                    phone: '',
                    email: '',
                },
            },
            editDialogVisible: false,
            editForm: {
                formConfig: [
                    {
                        type: 'input',
                        fieldName: 'name',
                        label: '用户名：',
                        disabled: true,
                    },
                    {
                        type: 'input',
                        fieldName: 'password',
                        label: '密码：',
                    },
                    {
                        type: 'input',
                        fieldName: 'type',
                        label: '用户类型：',
                        key: 'fold',
                        options: [
                            {
                                value: '7',
                                label: '普通用户',
                            },
                        ],
                    },
                    {
                        type: 'input',
                        fieldName: 'phone',
                        label: '手机号：',
                    },
                    {
                        type: 'input',
                        fieldName: 'email',
                        label: '邮箱：',
                    },
                ],
                otherConfig: {
                    title: '编辑用户',
                    cancelBtn: '取消',
                    saveBtn: '保存',
                },
                form: {
                    name: '1',
                    password: '2',
                    type: '3',
                    phone: '4',
                    email: '5',
                },
            },
            //迁移
            moveDialogVisible: false,
            moveForm: {
                otherConfig: {
                    title: '归属单位',
                    cancelBtn: '取消',
                    saveBtn: '保存',
                    options: ['-'],
                },
                form: {
                    checkedArr: [],
                },
            },
            deletDialogVisible: false,
        };
    },
    methods: {
        //分页
        onClickPaging(val) {
            this.facilityListA(this.Eid, val);
        },

        //新增设备
        addQquipment() {
            this.addForm.form = {name: '', password: '', type: '7', phone: '', email: ''};
            this.addDialogVisible = true;
        },
        //新增点击保存
        addSave(val) {
            const isValidPhoneNumber = num => /^\d{11}$/.test(num);
            const isValidEmail = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
            const {phone, email} = val;
            if (Object.keys(val).length === 5) {
                if (isValidEmail(email) && isValidPhoneNumber(phone)) {
                    facilityAdd(val)
                        .then(() => {
                            this.refreshData();
                            this.$message({
                                message: '新增成功',
                                type: 'success',
                            });
                            this.addDialogVisible = false;
                        })
                        .catch(err => {
                            console.log('err', err);
                            this.$message.error('新增失败');
                        });
                } else {
                    this.$message.error('请输入正确的邮箱和手机号');
                }
            } else {
                this.$message.error('请输入完整的信息');
            }
        },
        // 点击编辑-保存
        editSave(val) {
            const isValidPhoneNumber = num => /^\d{11}$/.test(num);
            const isValidEmail = email => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
            // 设置用户类型
            val.type = val.type === '普通用户' ? '7' : '8';
            val.id = this.deleteNews[this.amendId];
            const {phone, email} = val;
            if (isValidEmail(email) && isValidPhoneNumber(phone)) {
                facilityAdd1(val)
                    .then(res => {
                        this.refreshData();
                        this.$message({
                            message: '修改成功',
                            type: 'success',
                        });
                        this.editDialogVisible = false;
                    })
                    .catch(err => {
                        console.log('err', err);
                        this.$message.error('修改失败');
                    });
            } else {
                this.$message.error('请输入正确的邮箱和手机号');
            }
        },
        //点击编辑
        editRow(row) {
            this.amendId = '';
            this.editForm.form.name = row.test;
            this.editForm.form.password = this.password[row.test];
            this.editForm.form.type = row.test4;
            this.editForm.form.phone = row.test1;
            this.editForm.form.email = row.test3;
            this.amendId = row.test;
            this.editDialogVisible = true;
        },
        //归属单位
        moveShow(val) {
            this.equipmentTitle = {user_id: this.deleteNews[val.test]};
            this.moveDialogVisible = true;
        },
        moveSave(val) {
            let id = val.map(it => this.equipmentList[it]);
            this.equipmentTitle.ids = id.join(',');
            unitList(this.equipmentTitle)
                .then(() => {
                    this.$message({
                        message: '归属单位成功',
                        type: 'success',
                    });
                    this.moveForm.form.checkedArr = [];
                    // console.log('res', res);
                })
                .catch(err => {
                    console.log(err);
                });
            this.moveDialogVisible = false;
        },
        //点击删除
        deleteRow(val) {
            this.deleteId = this.deleteNews[val.test];
            this.deletDialogVisible = true;
        },
        //点击确认删除
        deletSave() {
            this.deletDialogVisible = false;
            this.loading = true;
            facilityDelete(this.deleteId).then(res => {
                this.loading = false;
                this.refreshData();
            });
        },
        refreshData() {
            this.ym = 1;
            facilityQuery(this.params)
                .then(res => {
                    if (res.status === 2) {
                        this.loading = false;
                        this.tableData = res.data.data.map((item, index) => ({
                            indexId: index + 1,
                            test: item.name,
                            test1: item.phone,
                            test3: item.email,
                            test4: item.data.type,
                            test5: item.data.status,
                            test6: item.atime,
                        }));
                        this.password = res.data.data.reduce((acc, val) => {
                            acc[val.name] = val.password;
                            return acc;
                        }, {});
                        this.deleteNews = res.data.data.reduce((acc, val) => {
                            acc[val.name] = val.id;
                            return acc;
                        }, {});
                        this.paging = res.data.totalPage * 10;
                    } else {
                        this.tableData = [];
                        this.loading = false;
                    }
                })
                .catch(err => {
                    console.log('err', err);
                    this.loading = false;
                    this.$message('查询失败');
                });
        },
        //查询
        queryUser() {
            console.log(this.params, '查询');
            this.loading = true;
            this.params.aid = JSON.parse(localStorage.getItem('userDetails'))?.id;
            this.refreshData();
        },
        facilityListA(id, val) {
            facilityList(id, val).then(res => {
                if (res.status === 2) {
                    this.tableData = res.data.data.map((item, index) => {
                        let i = (val - 1) * 10 + index + 1;
                        return {
                            indexId: i,
                            test: item.name,
                            test1: item.phone,
                            test3: item.email,
                            test4: item.data.type,
                            test5: item.data.status,
                            test6: item.atime,
                        };
                    });
                    this.paging = res.data.totalPage * 10;
                    this.password = res.data.data.reduce((acc, val) => {
                        acc[val.name] = val.password;
                        return acc;
                    }, {});
                    this.deleteNews = res.data.data.reduce((acc, val) => {
                        acc[val.name] = val.id;
                        return acc;
                    }, {});
                } else {
                    this.tableData = [];
                }
            });
        },
    },
    activated() {
        getUnitMap({
            name: '',
            paged: 1,
            pageSize: 50000,
        })
            .then(res => {
                this.equipmentList = res.data.data.reduce((obj, item) => {
                    obj[item.name] = item.id;
                    return obj;
                }, {});
                this.moveForm.otherConfig.options = res.data.data.map(item => item.name);
            })
            .catch(err => {
                console.log(err);
            });

        this.Eid = {aid: JSON.parse(localStorage.getItem('userDetails'))?.id};
        // eslint-disable-next-line no-undef
        this.facilityListA(this.Eid, 1);
        this.paging = 10;
    },

    mounted() {},
};
</script>
<style scoped>
.subaccount >>> .el-pagination {
    margin-bottom: 10px;
    width: 100%;
}
.subaccount >>> .el-pager li {
    background: rgba(4, 44, 91, 0.02);
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #0e5fff;
}
.subaccount >>> .btn-next {
    background: rgba(4, 44, 91, 0.02);
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #0e5fff;
}
.subaccount >>> .btn-prev {
    background: rgba(4, 44, 91, 0.02);
    border-radius: 5px 5px 5px 5px;
    border: 1px solid #0e5fff;
}
.subaccount >>> .table-class {
    display: flex;
    flex-direction: column;
}
</style>

<style scoped lang="scss">
.subaccount {
    padding: 0 10px;
    width: 100%;
    height: 100%;
    .el-loading-mask {
        background: none;
    }
    .bottom {
        background-image: url('@/assets/img/atlas-message.png');
        position: relative;
        background-size: 100% 100%;
        width: 100%;
        height: 100%;
        background-repeat: no-repeat;
        z-index: 2;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        align-items: center;

        .title {
            color: #19ecff;
            font-size: 14px;
        }

        .middle {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            color: #ffffff;
            width: 100%;
            padding: 20px 0 10px;
            flex-wrap: wrap;

            .el-input {
                width: 200px;
                margin-right: 10px;
            }

            ::v-deep .el-input__inner {
                background: #021045;
                border-radius: 4px 4px 4px 4px;
                border: 1px solid #00c2ff;
                font-size: 12px;
                height: 30px;
                width: 200px;
            }

            ::v-deep .el-button {
                background: #021c34;
                box-shadow: inset 0px 0px 8px 0px #00c2ff;
                border-radius: 4px 4px 4px 4px;
                color: #ffffff;
                font-size: 12px;
                padding: 0px 10px !important;
                // line-height: 20px;
                height: 30px;
                border: none;
            }
        }

        .middle-box {
            .el-input {
                width: 200px;
                margin-right: 10px;
            }

            ::v-deep .el-input__inner {
                background: #021045;
                border-radius: 4px 4px 4px 4px;
                border: 1px solid #00c2ff;
                font-size: 12px;
                height: 30px;
                width: 200px;
            }

            ::v-deep .el-button {
                background: #021c34;
                box-shadow: inset 0px 0px 8px 0px #00c2ff;
                border-radius: 4px 4px 4px 4px;
                color: #ffffff;
                font-size: 12px;
                padding: 0px 10px !important;
                // line-height: 20px;
                height: 30px;
                border: none;
                position: absolute;
                top: 10px;
                right: 20px;
            }
        }
    }
}
</style>
